package cc.ccoke.algorithms.primary.chapter01;

import cc.ccoke.algorithms.util.ArrayUtils;


/**
 * 归并排序
 * @author ccoke
 */
public class MergeSort {
    public static void sort(int[] arr, int left, int right) {
        if (left == right) {
            return;
        }
        // 获取数组中心
        int middle = (left + right) / 2;
        // 排序左边
        sort(arr, left, middle);
        sort(arr,middle + 1, right);
        marge(arr, left, middle, right);

    }

    private static void marge(int[] arr, int left, int middle, int right) {
        int[] temp = new int[right - left + 1];
        int index = 0;
        int p = left;
        int q = middle + 1;
        /**
         * 比较两边，小的优先插入数组
         */
        while (p <= middle && q <= right) {
            temp[index++] = arr[p] < arr[q] ? arr[p++] : arr[q++];
        }
        //右数组是否有剩余
        while (p <= middle) {
            temp[index++] = arr[p++];
        }
        //左数组是否有剩余
        while (q <= right) {
            temp[index++] = arr[q++];
        }
        // 改变原数组对应位置
        for (int i = 0; i < temp.length; i++) {
            arr[left + i] = temp[i];
        }
    }


    public static void main(String[] args) {
        int[] arr = ArrayUtils.generateByInt(10, 20);
        System.out.println("--- before ---");
        ArrayUtils.print(arr);
        System.out.println("--- after ---");
        sort(arr, 0, arr.length -1);
        ArrayUtils.print(arr);
    }

}
